<template>
    <div class="app-container">
        <div class="header-wrap">
          <el-form :model="queryParams" ref="queryForm" :inline="true" label-width="120px">
              <el-form-item label="资讯标题" prop="inviteMobile">
              <el-input v-model="queryParams.title" placeholder="请输入资讯标题" clearable size="small" style="width: 240px"
                  @keyup.enter.native="getInformationList" />
              </el-form-item>
              <el-form-item label="创建时间">
                  <el-date-picker
                  v-model="createTime"
                  size="small"
                  style="width: 240px"
                  value-format="yyyy-MM-dd"
                  type="daterange"
                  range-separator="-"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  ></el-date-picker>
              </el-form-item>

              <el-form-item label="状态" prop="status">
                  <el-select style="width: 240px" v-model="queryParams.status" placeholder="请选择" clearable size="small">
                  <el-option
                      v-for="status in informationStatus"
                      :key="status.dictValue"
                      :label="status.dictLabel"
                      :value="status.dictValue"
                  />
                  </el-select>
              </el-form-item>
              <el-form-item label="城市" prop="city">
                  <el-select style="width: 240px" v-model="queryParams.city" placeholder="请选择" clearable size="small">
                  <el-option
                      v-for="city in informationCities"
                      :key="city"
                      :label="city"
                      :value="city"
                  />
                  </el-select>
              </el-form-item>
              <el-form-item label="创建方式" prop="createBy">
                  <el-select style="width: 240px" v-model="queryParams.createBy" placeholder="请选择" clearable size="small">
                  <el-option
                      v-for="item in createTypes"
                      :key="item.text"
                      :label="item.text"
                      :value="item.value"
                  />
                  </el-select>
              </el-form-item>
              <el-form-item label="渠道" prop="channel">
                  <el-select style="width: 240px" v-model="queryParams.channel" placeholder="请选择" clearable size="small">
                  <el-option
                      v-for="item in channels"
                      :key="item.text"
                      :label="item.text"
                      :value="item.value"
                  />
                  </el-select>
              </el-form-item>
              <el-form-item label="作者" prop="inviteMobile">
              <el-input v-model="queryParams.author" placeholder="请输入作者" clearable size="small" style="width: 240px"
                  @keyup.enter.native="getInformationList" />
              </el-form-item>
              <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="getInformationList">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
          </el-form>
        </div>
        <el-button style="margin-bottom:15px" type="success" size="mini" @click="onCreateBtnClick">创建</el-button>
        <el-button style="margin-bottom:15px" type="primary" size="mini" @click="toggleShow('batchShow')">批量显示</el-button>
        <el-button style="margin-bottom:15px" type="info" size="mini" @click="toggleShow('batchHide')">批量隐藏</el-button>

        <el-table v-loading="loading" border :data="informationData" :row-key="getRowKeys" style="width: 100%" @selection-change="handleSelectionChange">
            <el-table-column
              align="center"
              type="selection"
              :reserve-selection='true'
              width="55">
            </el-table-column>
            <el-table-column label="资讯标题">
                <template slot-scope="scope">
                <span>{{ scope.row.title }}</span>
                </template>
            </el-table-column>
            <el-table-column label="城市">
                <template slot-scope="scope">
                  <el-popover
                    class="cityPopover"
                    placement="top-start"
                    trigger="hover"
                    width="240"
                    :content="scope.row.cities?scope.row.cities.join('、') : '暂无数据' ">
                    <div class="cityColumn" slot="reference">
                      <div class="cityDiv">{{scope.row.cities?scope.row.cities.join("、") : ''}}</div>
                      <div class="cityTotalDiv">{{scope.row.cities? '共'+scope.row.cities.length+'城':'-'}}</div>
                    </div>
                  </el-popover>
                </template>
            </el-table-column>
            <el-table-column label="渠道" width="100" align="center">
                <template slot-scope="scope">
                <span>{{ scope.row.channel }}</span>
                </template>
            </el-table-column>
            <el-table-column label="作者" width="170" align="center">
                <template slot-scope="scope">
                <span>{{ scope.row.author }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建时间" width="100" align="center">
                <template slot-scope="scope">
                <span>{{ scope.row.createTime }}</span>
                </template>
            </el-table-column>
            <el-table-column label="创建方式" width="100" align="center">
                <template slot-scope="scope">
                <span v-if=" scope.row.createBy==='云采集'">云采集</span>
                <span v-else>手动创建</span>
                </template>
            </el-table-column>
            <el-table-column label="状态" width="100" align="center">
                <template slot-scope="scope">
                  <template v-if="scope.row.status==1">未分段</template>
                  <template v-if="scope.row.status==2">显示</template>
                  <template v-if="scope.row.status==3">隐藏</template>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="200" class-name="small-padding fixed-width">
                <template slot-scope="scope">
                <el-button
                    size="mini"
                    type="text"
                    @click="previewInformation(scope.row)"
                    v-hasPermi="['reviewActivities:activities:remove']">
                    预览
                </el-button>
                <el-button
                    size="mini"
                    type="text"
                    @click="toggleShow(scope.row,scope.$index)"
                    v-hasPermi="['reviewActivities:activities:remove']">
                    <template v-if="scope.row.status==2">隐藏</template>
                    <template v-if="scope.row.status==3">显示</template>
                </el-button>
                <el-button
                    size="mini"
                    type="text"
                    @click="editInformation(scope.row)"
                    v-hasPermi="['reviewActivities:activities:remove']">
                    编辑
                </el-button>
                <el-button
                    size="mini"
                    type="text"
                    @click="deleteInformation(scope.row.id)"
                    v-hasPermi="['reviewActivities:activities:remove']">
                    删除
                </el-button>
                </template>
            </el-table-column>
        </el-table>
        <pagination v-show="informationData.length > 0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.rows"
        @pagination="getInformationList" />

        <!-- 资讯编辑界面 -->
        <el-dialog :close-on-click-modal="false" :before-close="closeEditDialog" :visible.sync="showEditIDialog" width="720px" append-to-body>
            <div>
              <div class="rowBox">
                  <div class="rowTitle">资讯标题</div>
                  <el-input class="input editTitleInput" placeholder="5-50个字" v-model="informationInfo.title" maxlength="50" size="small"/>
              </div>
              <div class="inputHint">
                <div v-show="isEmpty(informationInfo.title) || informationInfo.title.length < 5">资讯标题不能为空, 字数在5-50之间</div>
              </div>

              <div class="rowBox">
                  <div class="rowTitle">作者</div>
                  <el-input class="input" placeholder="最多10个字" v-model="informationInfo.author" maxlength="10" size="small"/>
              </div>
              <div class="inputHint">
                <div v-show="isEmpty(informationInfo.author)">作者不能为空, 最多10个字</div>
              </div>
              <div class="rowBox">
                  <div class="rowTitle">渠道</div>
                  <el-input class="input" placeholder="最多10个字" v-model="informationInfo.channel" maxlength="10" size="small"/>
              </div>
              <div class="inputHint">
                <div v-show="isEmpty(informationInfo.channel)">渠道不能为空, 最多10个字</div>
              </div>
              <div class="rowBox">
                  <div class="rowTitle">城市</div>
                  <div class="citySelector">
                      <el-checkbox :indeterminate="cityOptions.isIndeterminate" v-model="cityOptions.checkAll" @change="handleCitiesCheckAll">全选</el-checkbox>
                      <div style="margin-right:25px"></div>
                      <el-checkbox-group v-model="informationInfo.cities" @change="handleCitiesCheckedChange">
                          <el-checkbox v-for="city in informationCities" :label="city" :key="city">{{city}}</el-checkbox>
                      </el-checkbox-group>
                  </div>
              </div>

              <div class="uploadBox">
                  <div class="uploadTitle">资讯封面图</div>
                  <el-upload
                      class="upload"
                      action="https://api.shulanfd.com/aist-filesvr-web/api/files"
                      :data="{filetype:'资讯封面',app:'shulan',module:'1',sourceKey:'1'}"
                      list-type="picture"
                      :on-success="handleSuccess"
                      :on-remove="handleRemove"
                      :file-list="fileList"
                      :limit="1">
                      <el-button size="small" type="primary">点击上传</el-button>
                      <div slot="tip" class="el-upload__tip">封面尺寸：500kb</div>
                      <div slot="tip" class="el-upload__tip">扩展名类型：.jpg .jpeg .png</div>
                  </el-upload>
              </div>

              <div class="editorBox">
                <div class="rowTitle">正文<span class="full-screen" @click="fullScreenEditor">(全屏编辑)</span></div>
                <Editor :class="['editor',isFullScreenEditor ? 'full-screen' : '']" v-model="informationInfo.content" />
                <div v-if="isFullScreenEditor" @click="exitFullScreen" class="exit-full-screen">退出全屏</div>
              </div>

              <div class="extractHint">
                在富文本中要分割的段落前后插入"
                <span class="informationSeparator" v-on:click="copySeparator">{{separator}}</span>
                "用于提取内容，提取的内容会用于前台显示，点击预览可以查看实际展示效果
              </div>

              <div class="statusSelector">
                <div class="rowTitle">状态</div>
                <el-radio v-for="(status, index) in informationStatus" v-bind:key="index" v-model="informationInfo.status" :label="status.dictValue">
                  {{status.dictLabel}}
                </el-radio>
              </div>

              <div class="operations">
                <el-button type="success" size="medium" @click="segmentate">帮我分段</el-button>
                <el-button size="medium" @click="previewWhileEditing">预览</el-button>
                <el-button type="primary" size="medium" @click="saveInformation">保存</el-button>
              </div>

          </div>
        </el-dialog>

        <el-dialog :close-on-click-modal="true" title="预览" :visible.sync="showReviewDialog" width="375px" append-to-body>
          <div class="reviewBox">
            <div class="reviewTitle">{{informationInfo.title}}</div>
            <div class="aboutInformation">
              <span class="author">{{this.informationInfo.author}}</span>
              <span class="createDate">{{this.informationInfo.createTime}}</span>
            </div>

            <div v-for="(item, index) in previewData" v-bind:key="index">
              <div class="previewText" v-if="item.type === 0">{{item.content}}</div>
              <img class="previewImg" v-if="item.type === 1" :src="item.content">
            </div>
          </div>
        </el-dialog>

    </div>
</template>

<script>
import Editor from '@/components/Editor';
import Clipboard from 'clipboard';
import {
  getInformationList,
  getInformationDetial,
  getPreviewInfoWithId,
  updateConsultingStatus,
  getPreviewInfoWhileEditing,
  deleteInformation,
  updateInformation,
  saveInformation,
  segmentate
} from "@/api/reviewActivities/informationManage";

export default {
  name: "informationManage",
  components: { Editor },
  data() {
    return {
      multipleSelection: '',
      separator: "lt;%5i5j%gt;",
      informationTitle: null, // 资讯标题
      cityOptions: {
          CheckAll: false,
          isIndeterminate: false
      },
      fileList: [],
      content: null,
      tagState: true, //打标签按钮状态
      blackListState: false, //黑名单按钮状态
      queryParams: {
        page: 1,
        rows: 20,
        title: null,
        city: null,
        status: null,
        beginTime: null,
        endTime: null,
        channel: null,
        author: null
      },
      informationStatus: [],
      statusValues: [],
      informationCities:[],
      createTime:[],
      showEditIDialog: false,
      informationInfo: {
        cities: [],
        status: "2"
      },
      showReviewDialog: false, // 显示预览界面
      informationData: [], // 资讯列表数据
      total:0,  // 资讯列表总数
      loading: false,
      previewData:[],
      isFullScreenEditor:false, //是否全屏编辑
      createTypes:[
        {
        text:'不限',
        value:'all'
      },{
        text:'手动创建',
        value:'hand'
      },{
        text:'云采集',
        value:'auto'
      }],
      channels:[
       {
        text:'今日头条',
        value:'今日头条'
      }]
    }
  },

  created() {
    // 获取资讯状态字典
    this.getInformationStatus();
    // 获取资讯城市字典
    this.getInformationCity();
    // 获取资讯列表
    this.getInformationList();
  },

  methods: {
    // 帮我分段按钮事件
    segmentate(){
      let content = {content:this.informationInfo.content};
      if(!this.informationInfo.content){
        this.showHintDialog('分段内容不能为空');
        return;
      }
      segmentate(content).then(res => {
        console.log("分段 ---->", res);
        if (res.code === 200) {
          this.showHintDialog('分段完成，请点击预览查看分段效果')
          this.informationInfo.content = res.msg;
        }
      })
    },
    getRowKeys(row) {
   		return row.id;
	  },
    // 列表复选框事件
    handleSelectionChange(val) {
      let selectedList = val;
      let selectedListLength = selectedList.length;
      let tempArr = [];
      for(let i = 0; i < selectedListLength; i++){
        tempArr.push(selectedList[i].id)
      }
      this.multipleSelection = tempArr.toString();
      console.log(this.multipleSelection)
    },
    // 获取资讯状态字典
    getInformationStatus() {
        this.getDicts("information_status").then(response => {
          this.informationStatus = response.data;
          response.data.map((item) => {
            this.statusValues.push(item.dictValue);
          })
        })
    },

    // 获取资讯城市字典
    getInformationCity() {
      this.getDicts("information_city").then(response => {
          let cityArr = [];
          response.data.map(item => {
            cityArr.push(item.dictLabel);
          })
          this.informationCities = cityArr;
      })
    },

    // 获取资讯列表
    getInformationList() {
      this.loading = true;
      console.log("列表请求参数 -->",this.queryParams);
      if (this.createTime.length > 0) {
        this.queryParams.beginTime = this.createTime[0];
        this.queryParams.endTime = this.createTime[1];
      }
      getInformationList(this.queryParams)
        .then(res => {
          console.log("获取用户列表 ---->", res);
          if (res.code === 200) {
            this.informationData = res.data.consultingVoList;
            this.total = res.data.total;
            this.loading = false
          }
        })
    },

    // 城市全选操作
    handleCitiesCheckAll(val) {
        this.informationInfo.cities = val ? this.informationCities : [];
        this.cityOptions.isIndeterminate = false;
    },

    // 城市单选操作
    handleCitiesCheckedChange(value) {
        let checkedCount = value.length;
        this.cityOptions.checkAll = checkedCount === this.informationCities.length;
        this.cityOptions.isIndeterminate = checkedCount > 0 && checkedCount < this.informationCities.length;
    },

    // 图片上传成功
    handleSuccess(res, file) {
      this.informationInfo.thumbnail = "https://api.shulanfd.com/aist-filesvr-web/api/files/" + res[0].id;
    },

    // 删除图片回调
    handleRemove() {
      this.informationInfo.thumbnail = null;
      this.fileList = [];
    },

    // 重置头部筛选
    resetQuery() {
      this.createTime = [];
      this.queryParams.title = null;
      this.queryParams.beginTime = null;
      this.queryParams.endTime = null;
      this.queryParams.city = null;
      this.queryParams.status = null;
      this.queryParams.channel = null;
      this.queryParams.author = null;

      this.getInformationList();
    },

    // 创建资讯
    onCreateBtnClick() {
      this.informationInfo = {cities: [], status: "2"};
      this.showEditIDialog = true;
    },

    // 资讯列表预览
    previewInformation(row) {
      this.informationInfo.title = row.title;
      this.informationInfo.author = row.author;
      this.informationInfo.createTime = row.createTime;
      getPreviewInfoWithId({id: row.id})
        .then(res => {
          if (res.data) {
            this.handlePreviewData(res.data);
          }
        })
    },
    // 切换显示隐藏列表
    toggleShow(row,index) {
      let _this = this;
      let listData = this.informationData;
      let changeItem = listData[index];
      let status = row.status;
      let id = row.id;
      let tips = '';
      if(typeof row === 'string'){
        if(row === 'batchShow'){
          if(this.multipleSelection){
            id = this.multipleSelection;
            status=2;
            tips = '确定要批量显示所选的资讯吗？'
          }else{
            this.showHintDialog('请选择要显示的列表');
            return;
          }
        }else if(row === 'batchHide'){
          if(this.multipleSelection){
            id = this.multipleSelection;
            status=3;
            tips = '确定要批量隐藏所选的资讯吗？'
          }else{
            this.showHintDialog('请选择要隐藏的列表')
            return;
          }
        }
      }else{
        if(row.status==2){
          status=3;
          tips = '确定要隐藏该资讯吗？'
        }else if(row.status==3){
          status=2;
          tips = '确定要显示该资讯吗？'
        }
      }
      this.showConfirmDialog(tips,function(){
        updateConsultingStatus ({id,status})
          .then(res => {
            if (res.code === 200) {
              if(typeof row === 'string'){
                _this.getInformationList();
              }else{
                if(row.status==2){
                  changeItem.status = 3;
                  _this.informationData[index].status = 3;
                }else if(row.status==3){
                  _this.informationData[index].status = 2;
                }
              }
            }
          })
      });
    },

    // 编辑资讯
    editInformation(row) {
      this.showEditIDialog = true;
      // 获取资讯信息
      getInformationDetial({id: row.id})
        .then(res => {
          console.log("资讯详情 --->",res);
          console.log(res.data.cities.length , this.informationCities.length)
          if (res.code === 200) {
            // 处理城市选择状态
            if (res.data.cities == null) {
              res.data.cities = [];
            } else if (res.data.cities.length === this.informationCities.length) {
              this.cityOptions.checkAll = true;
            } else if (res.data.cities.length > 0 && res.data.cities.length < this.informationCities.length) {
              this.cityOptions.isIndeterminate = true;
            }

            if (res.data.thumbnail != null) this.fileList = [{name:"",url:res.data.thumbnail}];

            this.informationInfo = res.data;
          }
        })
    },

    // 删除资讯
    deleteInformation(id) {
      this.showConfirmDialog("确认删除平台与经纪人发布的此条资讯？", () => {
        deleteInformation(id)
          .then(res => {
            console.log("删除结果 --->",res);
            if (res.code === 200) {
              this.getInformationList();
            }
            this.showHintDialog(res.msg);
          })
      })
    },
    // 编辑时预览
    previewWhileEditing() {
      if (this.isEmpty(this.informationInfo.title) || this.informationInfo.title.length < 5) return this.showHintDialog("请填写正确的标题");
      if (this.isEmpty(this.informationInfo.author)) return this.showHintDialog("作者不能为空");
      if (this.isEmpty(this.informationInfo.content)) return this.showHintDialog("正文内容不能为空");
      getPreviewInfoWhileEditing(this.informationInfo.content)
      .then(res => {
        console.log("编辑时获取预览结果 --->",res);
        if (res.data) {
          this.handlePreviewData(res.data);
        }
      })
    },

    // 处理预览资讯数据
    handlePreviewData(previewData) {
      this.showReviewDialog = true;
      let data =[];
      previewData.map((group) => {
        group.map((item) => {
          data.push(item);
        })
      })
      this.previewData = data;
    },

    // 保存资讯
    saveInformation() {
      console.log("上传的图片信息 --->",this.fileList);
      if (this.isEmpty(this.informationInfo.title) || this.isEmpty(this.informationInfo.author) || this.isEmpty(this.informationInfo.channel)) return;
      // 标题字数少于5
      if (this.informationInfo.title.length < 5) return;

      if (this.informationInfo.cities && this.informationInfo.cities.length === 0) return this.showHintDialog("请选择城市");

      if (this.isEmpty(this.informationInfo.content)) return this.showHintDialog("富文本内容不能为空");

      if (this.informationInfo.status == null) return this.showHintDialog("请选择显示状态");

      if (this.informationInfo.id != null) {
        updateInformation(this.informationInfo)
          .then(res => {
            this.onSaveSuccess(res)
          })
      } else {
        saveInformation(this.informationInfo)
          .then(res => {
            this.onSaveSuccess(res)
          })
      }
    },

    // 保存成功的操作
    onSaveSuccess(res){
      console.log("保存资讯的结果 --->",res);
      if (res.code === 200) {
        this.showHintDialog("保存成功!",() => {
          this.showEditIDialog = false;
          this.getInformationList();
        })
      } else {
        this.showHintDialog("保存失败");
      }

    },

    // 关闭资讯编辑弹框的回调
    closeEditDialog(done) {
      // this.informationInfo = {cities: [], status: "2"};
      this.cityOptions.isIndeterminate = false;
      this.cityOptions.checkAll = false;
      this.fileList = [];
      done();
    },

    // 显示提示框
    showHintDialog(hint, callback) {
      this.$alert(hint, '提示', {
        confirmButtonText: '确定',
        callback: callback
      });
    },

    // 确认提示框
    showConfirmDialog(hint, callback) {
      this.$confirm(hint, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        callback();
      })
    },

    // 判断字符串是否为空
    isEmpty(str) {
      return (str == null || !(str.toString()) || str.toString().replace(/\s/g,"").length == 0);
    },

    // 复制分隔符
    copySeparator() {
      let clipboard = new Clipboard('.informationSeparator', {
         text: () => {// 注意this指向的问题
            return this.separator;
        }
      });

      console.log("开始复制 -->", clipboard)
      clipboard.on('success', e => {
          this.$message({
            message: this.separator + '  已复制到粘贴板',
            type: 'success'
          });
          // 释放内存
          clipboard.destroy()
        })
        clipboard.on('error', e => {
          // 不支持复制
          console.log('该浏览器不支持自动复制')
          // 释放内存
          clipboard.destroy()
        })
    },

    // 富文本编辑器全屏展示
    fullScreenEditor(){
      this.isFullScreenEditor = true;
    },

     // 富文本编辑器退出全屏
    exitFullScreen(){
      this.isFullScreenEditor = false;
    }
  }
}
</script>

<style lang="scss" scoped>
  .header-wrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .rowBox {
    display: flex;
    align-items: center;

    .input {
      width: 200px;
    }

    .editTitleInput {
      width: 350px;
    }
  }

  .rowTitle {
    width: 95px;
  }
   .rowTitle .full-screen{
     color:cornflowerblue;
     cursor: pointer;
  }
  .exit-full-screen{
    color: crimson;
    position:fixed;
    z-index: 2;
    right:30px;
    top:12px;
    font-size:16px;
    cursor: pointer;
  }
  .inputHint {
    height: 20px;
    color: red;
    font-size: 11px;
    margin-top: 5px;
    margin-left: 95px;
  }

  .citySelector {
    display: flex;
    flex: 1;
  }

  .uploadBox {
    display: flex;
    margin-top: 25px;

    .uploadTitle {
      margin-top: 7.5px;
      width: 95px;
    }
  }

  .editorBox {
    display: flex;
    height: 275px;
    margin-top: 25px;
  }

  .editor {
    flex: 1;
  }
  .extractHint {
      flex: 1;
      font-size: 12px;
      color: red;
      margin-left: 95px;

      .informationSeparator {
        color: rgba(65, 145, 250, 1);
      }
  }

  .statusSelector {
    display: flex;
    align-items: center;
    margin-top: 25px;
  }

  .operations {
      flex: 1;
      display: flex;
      margin-top: 25px;
      margin-left: 95px;
  }

  .reviewTitle {
    font-size: 15px;
    font-weight: 500;
  }

  .aboutInformation {
    margin-top: 10px;
    margin-bottom: 20px;
    font-size: 10px;

    .author {
      color: rgba(65, 145, 250, 1);
      margin-right: 15px;
    }
  }

  .previewText {
    font-size: 15px;
    margin-bottom: 15px;
  }

  .previewImg {
    width: 335px;
    margin-bottom: 15px;
  }

  .cityColumn {
    display: flex;
    align-items: center;
    color: rgba(65, 145, 250, 1);
    .cityDiv {
      flex: 1;
      display: -webkit-box;
      overflow: hidden; /*超出宽度部分隐藏*/
      text-overflow: ellipsis; /*超出部分以点号代替*/
      -webkit-line-clamp: 1; /*行数*/
      -webkit-box-orient: vertical;
    }
  }
</style>
<style lang="scss">
  .full-screen .editor{
    position:fixed;
    height: 100%;
    z-index: 1;
    top: 0;
    background: #fff;
    left: 0;
    right: 0;
    bottom: 0;
  }
</style>
